//
//  WNTool.m
//  Whatnet_iOS
//
//  Created by Bill on 2019/5/3.
//  Copyright © 2019 什么网络. All rights reserved.
//

#import "WNTool.h"
#include "sys/utsname.h"
#import <AVFoundation/AVFoundation.h>
#import "WNLoading.h"
static WNTool *instance = nil;
static NSDictionary *netCodeDict = nil;//错误码集合（从本地plist读取）

@interface  WNTool()

@property(nonatomic,strong)AVAudioPlayer *movePlayer;

@end


@implementation WNTool
#pragma mark - 初始化
+ (id)shared
{
    if (instance) return instance;
    return [[self alloc] init];
}

+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

+ (id)showLoading
{
    UIView *view = [[UIApplication sharedApplication] keyWindow];
    return [self showCustomImageViewWithView:view message:nil];
}

+ (id)showLoadingView:(UIView *)view
{
    return [self showCustomImageViewWithView:view message:nil];
}
+ (id)showLoadingMessage:(NSString *)message
{
    return [self showCustomImageViewWithView:WNApp.delegate.window message:message];
}
+ (MBProgressHUD *)showLoadingMessage:(NSString *)message view:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:NO];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:NO];
    [view bringSubviewToFront:hud];
    [hud hideAnimated:YES afterDelay:30.0];
    hud.label.text = message;
    return hud;
}

+ (BOOL)hideLoading
{
    return [self hideLoadingView:WNApp.delegate.window];
}

+ (BOOL)hideLoadingView:(UIView *)view
{
    MBProgressHUD *hud =  [MBProgressHUD HUDForView:view];
    if ([hud.customView isKindOfClass:[UIImageView class]]) {
        UIImageView *imageView = (UIImageView *)hud.customView;
        [imageView stopAnimating];
    }
    return [MBProgressHUD hideHUDForView:view animated:NO];
}

+ (void)showVieoProgress:(CGFloat)progress message:(NSString *)message{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIView *view = [[UIApplication sharedApplication] keyWindow];
        MBProgressHUD *hud = [MBProgressHUD HUDForView:view];
        if (progress == 0) {
            hud.detailsLabel.text = message;
        }else{
            CGFloat value = progress * 100;
            if (value > 100) {
                value = 100.f;
            }
            if (value < 0) {
                value = 0.f;
            }
            hud.detailsLabel.text = [NSString stringWithFormat:@"%@%0.f%%",message,value];
        }
    });
}


// 信息提示
+ (id)show:(NSString *)string
{
    if(string.length == 0)
        return nil;
    UIView *view = [[UIApplication sharedApplication] keyWindow];
    if (view == nil) return nil;
    return [self show:string inView:view];
}

// 网络信息提示
+ (id)showWithCode:(NSInteger )code
{
    return [self show:[self strWithCode:code]];
}

+ (id)showCustomImageViewWithView:(UIView *)view message:(NSString *)message{
    WNLoading *lodingView = [WNLoading new];
    [MBProgressHUD hideHUDForView:view animated:YES];
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:view];
    hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
//    hud.bezelView.color = [ThemeColor colorWithAlphaComponent:0.9];
    hud.mode = MBProgressHUDModeIndeterminate;
//    hud.customView = lodingView;
    if (message.length > 0) {
        hud.minSize = CGSizeMake(90, 90);
        hud.detailsLabel.text = message;
        hud.detailsLabel.textColor = [UIColor blackColor];
        hud.margin = 10;
    }else{
        hud.margin = 15;
    }
    hud.square = YES;
    hud.userInteractionEnabled = YES;
    hud.removeFromSuperViewOnHide = YES;
    [view addSubview:hud];
    [hud showAnimated:YES];
    [lodingView startAnimating];
    return hud;
}

+ (id)show:(NSString *)string inView:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:YES];
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:view];
    hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    hud.userInteractionEnabled = NO;
    hud.removeFromSuperViewOnHide = YES;
    hud.mode = MBProgressHUDModeText;
    hud.detailsLabel.text = string;
    hud.detailsLabel.textColor = [UIColor blackColor];
    [view addSubview:hud];
    [hud showAnimated:YES];
    [hud hideAnimated:YES afterDelay:2.0];
    return hud;
}

+ (MBProgressHUD *)showProgress:(NSString *)string inView:(UIView *)view
{
    [MBProgressHUD hideHUDForView:view animated:YES];
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:view];
    hud.userInteractionEnabled = NO;
    hud.removeFromSuperViewOnHide = YES;
    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
    hud.detailsLabel.text = string;
    [view addSubview:hud];
    [hud showAnimated:YES];
    return hud;
}

+ (void)delay:(double_t)seconds withBlock:(dispatch_block_t)block
{
    if (block == nil) return;
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (seconds * NSEC_PER_SEC));
    dispatch_after(time, dispatch_get_main_queue(), block);
}

/// 渐变效果
+ (CATransition *)addFadeAnimationWithDuration:(CFTimeInterval)duration
{
    NSString *direction = kCATransitionFromRight;
    NSString *function = kCAMediaTimingFunctionEaseIn;
    return [self addAnimationType:kCATransitionFade direction:direction duration:duration function:function];
}

/// 推送效果
+ (CATransition *)addPushAnimationWithDirection:(NSString*)direction
{
    return [self addAnimationType:kCATransitionReveal direction:direction duration:0.3 function:kCAMediaTimingFunctionLinear];
}

+ (CATransition *)addAnimationType:(NSString *)type direction:(NSString *)direction
{
    return [self addAnimationType:type direction:direction duration:0.3];
}

+ (CATransition *)addAnimationType:(NSString *)type direction:(NSString *)direction duration:(CFTimeInterval)time
{
    return [self addAnimationType:type direction:direction duration:time function:kCAMediaTimingFunctionDefault];
}

+ (CATransition *)addAnimationType:(NSString *)type direction:(NSString *)direction duration:(CFTimeInterval)time function:(NSString *)fuction
{
    CATransition*animation=[CATransition animation];
    //设置动画效果
    [animation setType:type];
    //设置动画方向
    [animation setSubtype:direction];
    //设置动画播放时间
    [animation setDuration:time];
    //设置动画作用范围
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:fuction]];
    return animation;
}
+ (NSString *)captureStatus
{
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusNotDetermined) return @"未授权";
    if (status == AVAuthorizationStatusRestricted) return@"有限权限";
    if (status == AVAuthorizationStatusDenied) return @"已拒绝";
    if (status == AVAuthorizationStatusAuthorized) return @"正常";
    return @"获取失败";
}
+ (NSString *)deviceString
{
    struct utsname utsname;
    uname(&utsname);
    NSString *machine = [NSString stringWithCString:utsname.machine encoding:NSUTF8StringEncoding];
    if ([machine isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([machine isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([machine isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([machine isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([machine isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
    if ([machine isEqualToString:@"iPhone3,3"])    return @"iPhone 4";
    if ([machine isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([machine isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([machine isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([machine isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    if ([machine isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    if ([machine isEqualToString:@"iPhone6,1"])    return @"iPhone 5S";
    if ([machine isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    if ([machine isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([machine isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([machine isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([machine isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([machine isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    if ([machine isEqualToString:@"iPhone9,1"])    return @"iPhone 7";
    if ([machine isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus";
    if ([machine isEqualToString:@"iPhone9,3"])    return @"iPhone 7";
    if ([machine isEqualToString:@"iPhone9,4"])    return @"iPhone 7 Plus";
    if ([machine isEqualToString:@"iPhone10,1"])    return @"iPhone 8";
    if ([machine isEqualToString:@"iPhone10,2"])    return @"iPhone 8 Plus";
    if ([machine isEqualToString:@"iPhone10,4"])    return @"iPhone 8";
    if ([machine isEqualToString:@"iPhone10,5"])    return @"iPhone 8 Plus";
    if ([machine isEqualToString:@"iPhone10,5"])    return @"iPhone 8 Plus";
    if ([machine isEqualToString:@"iPhone10,3"])    return @"iPhone X";
    if ([machine isEqualToString:@"iPhone10,6"])    return @"iPhone X";
    if ([machine isEqualToString:@"i386"])         return @"Simulator";
    if ([machine isEqualToString:@"x86_64"])       return @"Simulator";
    if ([machine hasPrefix:@"iPad"]) return @"iPad";
    if ([machine hasPrefix:@"iPod"]) return @"iPod";
    return @"iOS设备";
}
+ (NSString *)deviceUDID
{
    NSString *udid = [WNCache getValueForKey:@"UDID"];
    if (udid.length == 0){      // 钥匙串中获取
        udid = [self keychainObjectWithKey:@"UDID"];
        if (udid.length == 0) { // 重新生成写入钥匙串
            UIDevice *dev =  [UIDevice currentDevice];
            udid = dev.identifierForVendor.UUIDString;
            [self keychainSaveObject:udid forKey:@"UDID"];
        }
        [WNCache saveValue:udid forKey:@"UDID"];
    }
    return udid;
}
#pragma mark - 钥匙串操作
/// 写入钥匙串
+ (void)keychainSaveObject:(id)object forKey:(NSString *)key
{
    NSMutableDictionary *query = [self keychainQueryWithKey:key];
    SecItemDelete((__bridge_retained CFDictionaryRef)query);
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object];
    [query setObject:data forKey:(__bridge_transfer id)kSecValueData];
    SecItemAdd((__bridge_retained CFDictionaryRef)query, NULL);
}
/// 钥匙串取值
+ (id)keychainObjectWithKey:(NSString *)key
{
    id ret = nil;
    NSMutableDictionary *query = [self keychainQueryWithKey:key];
    //Configure the search setting
    [query setObject:(id)kCFBooleanTrue forKey:(__bridge_transfer id)kSecReturnData];
    [query setObject:(__bridge_transfer id)kSecMatchLimitOne forKey:(__bridge_transfer id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((__bridge_retained CFDictionaryRef)query, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge_transfer NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", key, e);
        } @finally {
            NSLog(@"Unarchive of %@ success!", key);
        }
    }
    return ret;
}
+ (NSMutableDictionary *)keychainQueryWithKey:(NSString *)key
{
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (__bridge_transfer id)kSecClassGenericPassword,(__bridge_transfer id)kSecClass,
            key, (__bridge_transfer id)kSecAttrService,
            key, (__bridge_transfer id)kSecAttrAccount,
            (__bridge_transfer id)kSecAttrAccessibleAfterFirstUnlock,(__bridge_transfer id)kSecAttrAccessible,
            nil];
}
+ (void)keychainDeleteObjectWithKey:(NSString *)key
{
    NSMutableDictionary *query = [self keychainQueryWithKey:key];
    SecItemDelete((__bridge_retained CFDictionaryRef)query);
}

+ (NSString *)getLaunchImageName
{
    // 取当前屏幕尺寸
    CGSize viewSize = WNScreenSize;
    
    NSString *launchImage = nil;
    NSArray *imagesDict = [[WNMainBundle infoDictionary] valueForKey:@"UILaunchImages"];
    for(NSDictionary *dict in imagesDict) {
        // 遍历各字典中尺寸大小及图像方向，找到我们需要的那张图
        CGSize imageSize = CGSizeFromString([dict sa_objectForKey:@"UILaunchImageSize"]);
        NSString *orientation = [dict sa_objectForKey:@"UILaunchImageOrientation"];
        
        if (CGSizeEqualToSize(imageSize, viewSize) && [orientation isEqualToString:@"Portrait"]) {
            launchImage = [dict sa_objectForKey:@"UILaunchImageName"];
        }
    }
    return launchImage;
}

+ (UIViewController *)getCurrentVC {
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        result = nextResponder;
    } else {
        result = window.rootViewController;
    }
    return result;
}

//网络请求Code对应的提示
+ (NSString *)strWithCode:(NSInteger)code{
    if (!netCodeDict) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"neStatustCode" ofType:@"plist"];
        netCodeDict = [NSDictionary dictionaryWithContentsOfFile:path];
    }
    NSString *key = [@(code) stringValue];
    NSString *str = netCodeDict[key];
    if (code < 0) {
        str = @"网络有误，请点击重试";
    }
    if (code == 0) {
        str = @"暂无数据~~";
    }
    return str;
}

//转换一下错误提醒文字
+ (NSAttributedString *)requestErrorWithSting:(NSString *)string{
    if (!string) {
        string = @"";
    }
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
    //字体大小
    [attributeString addAttribute:NSFontAttributeName
                     value:[UIFont systemFontOfSize:15.0]
                     range:NSMakeRange(0, string.length)];
    //字体颜色
    [attributeString addAttribute:NSForegroundColorAttributeName
                      value:WNHexColor(0xDEDEDE)
                      range:NSMakeRange(0, string.length)];
    
    //段落
    NSMutableParagraphStyle   *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentCenter;//文本对齐方式 左右对
    [attributeString addAttribute:NSParagraphStyleAttributeName
                            value:paragraphStyle
                            range:NSMakeRange(0, string.length)];//设置段落样式
    return [attributeString copy];
}


//评论排版
+ (NSAttributedString *)commentWithString:(NSString *)string{
    if (!string) {
        string = @"";
    }
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
    //字体大小
    [attributeString addAttribute:NSFontAttributeName
                            value:[UIFont systemFontOfSize:14.0]
                            range:NSMakeRange(0, string.length)];
    //字体颜色
    [attributeString addAttribute:NSForegroundColorAttributeName
                            value:WNHexColor(0xffffff)
                            range:NSMakeRange(0, string.length)];
    
    //段落
    NSMutableParagraphStyle   *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 5;
    [attributeString addAttribute:NSParagraphStyleAttributeName
                            value:paragraphStyle
                            range:NSMakeRange(0, string.length)];//设置段落样式
    return [attributeString copy];
}

//字体添加阴影
+ (NSAttributedString *)shadowWithString:(NSString *)string font:(UIFont *)font fontColor:(UIColor *)fontColor{
    return [self shadowWithString:string font:font fontColor:fontColor shadowColor:[ThemeColor colorWithAlphaComponent:0.2] shadowOffset:CGSizeMake(1.0, 1.0)];
}

//字体添加阴影
+ (NSAttributedString *)shadowWithString:(NSString *)string
                                    font:(UIFont *)font
                               fontColor:(UIColor *)fontColor
                             shadowColor:(UIColor *)shadowColor
                             shadowOffset:(CGSize )shadowOffset
{
    if (!string) {
        string = @"";
    }
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:string];
    //字体大小
    [attributeString addAttribute:NSFontAttributeName
                            value:font
                            range:NSMakeRange(0, string.length)];
    //字体颜色
    [attributeString addAttribute:NSForegroundColorAttributeName
                            value:fontColor
                            range:NSMakeRange(0, string.length)];
    
    //阴影
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowBlurRadius = .5;
    shadow.shadowOffset = shadowOffset;
    shadow.shadowColor = shadowColor;
    [attributeString addAttribute:NSShadowAttributeName
                            value:shadow
                            range:NSMakeRange(0, string.length)];
    return [attributeString copy];
}

//获取当前版本号
+ (NSString *)currentAppVersion {
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleShortVersionString"];
}

/**
 比较两个版本号的大小
 
 @param v1 第一个版本号
 @param v2 第二个版本号
 @return 版本号相等,返回0; v1小于v2,返回-1; 否则返回1.
 */
+ (NSInteger)compareVersion2:(NSString *)v1 to:(NSString *)v2 {
    // 都为空，相等，返回0
    if (!v1 && !v2) {
        return 0;
    }
    
    // v1为空，v2不为空，返回-1
    if (!v1 && v2) {
        return -1;
    }
    
    // v2为空，v1不为空，返回1
    if (v1 && !v2) {
        return 1;
    }
    
    // 获取版本号字段
    NSArray *v1Array = [v1 componentsSeparatedByString:@"."];
    NSArray *v2Array = [v2 componentsSeparatedByString:@"."];
    // 取字段最大的，进行循环比较
    NSInteger bigCount = (v1Array.count > v2Array.count) ? v1Array.count : v2Array.count;
    
    for (int i = 0; i < bigCount; i++) {
        // 字段有值，取值；字段无值，置0。
        NSInteger value1 = (v1Array.count > i) ? [[v1Array objectAtIndex:i] integerValue] : 0;
        NSInteger value2 = (v2Array.count > i) ? [[v2Array objectAtIndex:i] integerValue] : 0;
        if (value1 > value2) {
            // v1版本字段大于v2版本字段，返回1
            return 1;
        } else if (value1 < value2) {
            // v2版本字段大于v1版本字段，返回-1
            return -1;
        }
        
        // 版本相等，继续循环。
    }
    
    // 版本号相等
    return 0;
}

//判断当前时间
+ (BOOL)judgeTime{
    NSDate *nowDate = [NSDate date];
    NSDate *targetDate = [NSDate wn_getDate:@"2019-08-01 11:33" format:@"yyyy-MM-dd HH:mm"];
    NSComparisonResult res = [nowDate wn_compare:targetDate format:@"yyyy-MM-dd HH:mm"];
    if (res == NSOrderedDescending) {
        //到时间了
        return YES;
    }else{
        //未到时
        return NO;
    }
}

//获取当前屏幕显示的viewcontroller
+ (UIViewController *)topViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

+ (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}



- (void)playlocalmusic:(NSString *)name number:(NSInteger)number{
    
    NSURL*moveMP3=[NSURL fileURLWithPath:[[NSBundle mainBundle].resourcePath stringByAppendingPathComponent:name]];
    NSError*err=nil;
    self.movePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:moveMP3 error:&err];
    self.movePlayer.volume = 1.0;
    [self.movePlayer prepareToPlay];
    if(err!=nil){
        NSLog(@"move player init error:%@",err);
    }else{
        self.movePlayer.numberOfLoops = number;
        [self.movePlayer play];
    };
}


- (void)stopPlayMusic{
    [self.movePlayer stop];
}


//图片转字符串
+(NSString *)UIImageToBase64Str:(UIImage *) image
{
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

//字符串转图片
+(UIImage *)Base64StrToUIImage:(NSString *)_encodedImageStr
{
    NSData *decodedImageData = [[NSData alloc]initWithBase64EncodedString:_encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
    UIImage *decodedImage = [UIImage imageWithData:decodedImageData];
    
    return decodedImage;
}


@end
